# include "config.h"

Configuration * newConfiguration (const char *name, const char *value) {
	Configuration *new = (Configuration *) malloc(sizeof(Configuration));
	if (!new) logMessage("io.files.config","config.c","newConfiguration","Mem. Insuf.",CRITICAL);
	new->name = strdup(name);
	new->value = strdup(value);
	return new;
}

void freeConfiguration (Configuration *c) {
	if (c) {
		free(c->name); free(c->value);
		free(c);
	}
}
static Configuration * readConfig (FILE *fp) {
	char name[MAXTAM], value[MAXTAM];
	int i = 0;
	char c = fgetc(fp);
	while (c != EOF && c != EQUAL_CHAR) {
		name[i++] = c;
		c = fgetc(fp);
	}
	name[i] = 0;
	if (i>0&&c!=EOF) {
		i = 0;
		c = fgetc(fp);
		while (c != EOF && c != '\n') {
			value[i++] = c;
			c = fgetc(fp);
		}
		value[i] = 0;
		if (i>0) return newConfiguration(name,value);
		else return NULL;
	} else {
		return NULL;
	}
}
LinkedList * readConfiguration (FILE *fp) {
	LinkedList *lst = NULL;
	Configuration *cfg = readConfig(fp);
	while (cfg) {
		lst = insertElemHead(lst,cfg);
		cfg = readConfig(fp);
	}
	return lst;
}

int writeConfiguration (LinkedList *list, FILE *fp) {
	LinkedList *aux = list;
	Configuration *tmp;
	while (aux) {
		tmp = getData(aux);
		fprintf(fp,"%s%c%s\n",tmp->name,EQUAL_CHAR,tmp->value);
		aux = aux -> next;
	}
	return 1;
}

void freeConfigurations (LinkedList *lst) {
	LinkedList *aux = lst;
	while (aux) {
		freeConfiguration(getData(aux));
		aux = aux->next;
	}
}
